package com.infore.airsupervise.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.bigkoo.pickerview.TimePickerView;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.PointDataQueryAdapter;
import com.infore.airsupervise.adapter.PointQueryRecyclerAdapter;
import com.infore.airsupervise.adapter.StationExpandAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.MenuE;
import com.infore.airsupervise.bean.PointQueryE;
import com.infore.airsupervise.biz.StatisticsBiz;
import com.infore.airsupervise.biz.impl.StatisticsBizImpl;
import com.infore.airsupervise.http.BaseResponse;
import com.infore.airsupervise.http.HttpUtil;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.fragment.StationTreeFragment;
import com.infore.airsupervise.ui.fragment.StatisticsDrawerFragment;
import com.infore.airsupervise.ui.widget.EmptyView;
import com.infore.airsupervise.utils.DateUtil;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import retrofit2.Call;

/**
 * 站点对比界面
 */
public class PointAnalyzeQueryActivity extends BaseTitleBarActivity {

    @BindView(R.id.chart_recycler_view)
    RecyclerView chartRecycler;
    @BindView(R.id.drawer_container)
    FrameLayout drawerContainer;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.tv_startTime)
    TextView tvStartTime;
    @BindView(R.id.tv_endTime)
    TextView tvEndTime;
    @BindView(R.id.emptyView)
    EmptyView emptyView;

    private StationTreeFragment drawerFrag;    // 抽屉Fragment
    private StatisticsBiz statisticsBiz;    // 业务类

    private TextView tvTitle; //时间选择器标题
    private TimePickerView timePickerView = null;

    private boolean[][] showType = new boolean[][]{
            {true, true, true, true, false, false},
            {true, true, true, false, false, false},
            {true, true, false, false, false, false}};

    private int dateType; //月 日 时
    private String startTime;
    private String endTime;
    private String curMNs = "";

    private boolean flag ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_point_analyze_query);
        ButterKnife.bind(this);

        statisticsBiz = new StatisticsBizImpl();

        initView();
    }

    private void initView() {
        // 获取携带数据
        Bundle bundle = getIntent().getExtras();
        final MenuE menuE = (MenuE) bundle.getSerializable(Constants.INTENT_OBJ_KEY);

        // 初始化标题栏
        title.setText(menuE.getTitle());
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_FILTER);

        //标识
        flag = false ;

        //时间
        resetSelTime(DateUtil.FORMAT_DATE_HOUR ,Calendar.DAY_OF_MONTH, -1);
        chartRecycler.setLayoutManager(new LinearLayoutManager(ctx));

        // 提示选择站点
        //ToastUtil.showLong(this, "请选择站点进行分析");
        chartRecycler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(!isFinishing()) {
                    getPointQueryDatas();
                }
            }
        },500);

    }

    /**
     * 时间选择器
     */
    private void initTimePicker() {
        Calendar endSelectedDate = Calendar.getInstance();
        timePickerView = new TimePickerView.Builder(ctx, timeSelectListener)
                .setTitleText("")
                .setLabel("年", "月", "日", "点", "分", "秒")
                .setType(showType[dateType])
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(18)
                .setRangDate(null, endSelectedDate)
                .setDate(endSelectedDate)
                .setDecorView(null)
                .build();
        tvTitle = (TextView) timePickerView.findViewById(com.bigkoo.pickerview.R.id.tvTitle);
    }

    /**
     * 获取远程数据
     */
    private void getPointQueryDatas() {
        final SweetAlertDialog dialog = new SweetAlertDialog(ctx, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING);
//        dialog.setCancelable(false);
        dialog.show();

        Call<BaseResponse> call = statisticsBiz.getPointAnalyzeQuery(dateType, startTime, endTime, curMNs,
                new OnServerResponseListener<List<PointQueryE>>() {
                    @Override
                    public void onSucceed(List<PointQueryE> result, String desc) {
                        dialog.dismiss();
                        // 数据少于两组时提示
                        if (result.size() < 2) {
//                            dialog.setTitleText("部分站点数据为空")
//                                    .setContentText("请选择有数据的站点进行分析")
//                                    .changeAlertType(SweetAlertDialog.WARNING_TYPE);
                            chartRecycler.setVisibility(View.GONE);
                            emptyView.setVisibility(View.VISIBLE);
                            emptyView.setShowInfo(R.drawable.status_search_null, MsgConst.EMPTY_DATA);
                        }else {
                            chartRecycler.setVisibility(View.VISIBLE);
                            emptyView.setVisibility(View.GONE);
                            if (flag == false) {
                                PointQueryRecyclerAdapter adapter = new PointQueryRecyclerAdapter(result, dateType);
                                chartRecycler.setAdapter(adapter);
                            } else {
                                PointDataQueryAdapter adapter = new PointDataQueryAdapter(result);
                                chartRecycler.setAdapter(adapter);
                            }
                        }
                    }

                    @Override
                    public void onFailed(int errorCode, String title, String desc) {
                        dialog.dismiss();
                        emptyView.setShowInfo(HttpUtil.getEmptyRes(errorCode),title);
                        emptyView.setVisibility(View.VISIBLE);
                        chartRecycler.setVisibility(View.GONE);
                    }
                });

        requests.add(call);
    }

    @Override
    protected void onRightMenuClick(View view) {
        super.onRightMenuClick(view);
        PopupMenu popupMenu = new PopupMenu(ctx, rightMenu);
        popupMenu.getMenuInflater().inflate(R.menu.data_type_menu, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                String format = null ;
                int calendarField  = Calendar.HOUR_OF_DAY;
                switch (menuItem.getItemId()){
                    case R.id.menu_hour :
                        dateType = StatusConst.STATISTIC_HOUR ;
                        format = DateUtil.FORMAT_DATE_HOUR;
                        calendarField =  Calendar.HOUR_OF_DAY;
                        break;
                    case R.id.menu_day :
                        dateType = StatusConst.STATISTIC_DAY ;
                        format = DateUtil.FORMAT_DATE;
                        calendarField =  Calendar.DAY_OF_MONTH;
                        break;
                    case R.id.menu_month :
                        dateType = StatusConst.STATISTIC_MONTH ;
                        format = DateUtil.dateFormatYM;
                        calendarField =  Calendar.MONTH;
                        break;
                }
                //重置时间
                if(null != format){
                    resetSelTime(format, calendarField , -1);
                }
                initTimePicker();
                getPointQueryDatas();
                return true;
            }
        });
        popupMenu.show();
    }
    /**
     * 站点抽屉布局按钮点击监听
     */
    private StationTreeFragment.OnClickListener onClicklistener = new StationTreeFragment.OnClickListener() {
        @Override
        public void onConfirmClick(String mn) {
            if(mn != null){
                curMNs = mn;
                getPointQueryDatas();
            }
            drawerLayout();
        }

        @Override
        public void onConfirmClick(String mn, String name) {

        }

        @Override
        public void onCancelClick() {
            drawerLayout();
        }
    };

    /**
     * 按钮点击事件监听
     * @param view
     */
    @OnClick({R.id.sel_station, R.id.tv_startTime, R.id.tv_endTime , R.id.emptyView})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sel_station:
                if(drawerFrag == null){
                    // 添加抽屉Fragment
                    drawerFrag = new StationTreeFragment();
                    drawerFrag.setCurType(StationExpandAdapter.CB_SELECTE);
                    drawerFrag.setOnClickListener(onClicklistener);
                    getSupportFragmentManager().beginTransaction().replace(R.id.drawer_container, drawerFrag).commit();
                }
                drawerLayout();
                break;
            case R.id.tv_startTime:
            case R.id.tv_endTime:
                if(timePickerView == null){
                    initTimePicker();
                }
                tvTitle.setText(view.getId() == R.id.tv_startTime ? "开始时间":"结束时间");
                timePickerView.show(view);
                break;
            case R.id.emptyView :
                getPointQueryDatas();
                break;
        }
    }

    /**
     * 时间选择事件监听
     */
    private TimePickerView.OnTimeSelectListener timeSelectListener = new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            if(dateType == StatusConst.STATISTIC_HOUR) {
                Calendar selector = Calendar.getInstance();
                Calendar endCalendar = Calendar.getInstance();
                selector.setTime(date);
                if (endCalendar.compareTo(selector) != 1) {
                    ToastUtil.showShort(ctx, "不能超过当前日期");
                    return;
                }
            }
            String timeFormat = getTimeFormat();
            switch (v.getId()){
                case R.id.tv_startTime:
                    if(DateUtil.compareDate(DateUtil.stringToDate(endTime,timeFormat) ,date )<= 0 ){
                        ToastUtil.showShort(ctx, "开始时间不能大于结束时间");
                    }else {
                        startTime = DateUtil.getStringByFormat(date,timeFormat);
                        tvStartTime.setText(startTime);
                        getPointQueryDatas();
                    }
                    break;
                case R.id.tv_endTime:
                    if(DateUtil.compareDate(date,DateUtil.stringToDate(startTime,timeFormat)) <= 0){
                        ToastUtil.showShort(ctx, "开始时间不能大于结束时间");
                    }else {
                        endTime = DateUtil.getStringByFormat(date, timeFormat);
                        tvEndTime.setText(endTime);
                        getPointQueryDatas();
                    }
                    break;
            }
        }
    };


    /**
     * 控制抽屉开关
     */
    private void drawerLayout(){
        if (!drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.openDrawer(Gravity.LEFT);
        } else {
            drawerLayout.closeDrawers();
        }
    }

    /**
     * 获取时间格式
     * @return
     */
    private String getTimeFormat(){
        if (dateType == StatusConst.STATISTIC_DAY) {
            return  DateUtil.FORMAT_DATE;
        } else if (dateType == StatusConst.STATISTIC_HOUR) {
            return DateUtil.FORMAT_DATE_HOUR ;
        } else {
            return DateUtil.dateFormatYM ;
        }
    }

    /**
     * 重置时间
     */
    private void resetSelTime(String format ,int calendarField ,int offset ){
        startTime = DateUtil.getStringByOffset(Calendar.getInstance().getTime(),format,calendarField,offset);
        endTime = DateUtil.getCurrentDateStr(format);
        tvStartTime.setText(startTime);
        tvEndTime.setText(endTime);
    }

}
